<?php

namespace SC\Admin\Widgets;


class Grid extends Panel
{
    protected $view = 'admin::widgets.grid';

    protected $model = null;
    protected $descID = null;
    protected $perPage = 20;
    protected $orderBy = null;
    protected $searchable = true;

    public function __construct($model)
    {
        $this->model = $model;
    }

    protected function buildPagination()
    {
        $query = $this->model::where(function(){});
        if ($this->searchable && $reqQuery = request('q')) {
            if (\is_numeric($reqQuery)) {
                $query->where('id', $reqQuery);
            } else {
                $query->whereRaw($reqQuery);
            }
        }

        if ($this->query) {
            $this->query->bindTo($query)();
        }

        if ($this->descID || (\is_null($this->descID) && \is_null($this->orderBy))){
            $query->orderBy('id', 'DESC');
        }
        if ($this->orderBy) {
            $query->orderBy($this->orderBy);
        }

        try {
            return $query->paginate($this->perPage)->appends(['q' => request('q')]);
        } catch (QueryException $e) {
            //todo
        }
        return null;
    }

    protected function gridValue($collection)
    {
        $gridValue = [];
        if (\is_null($collection)) {
            return $gridValue;
        }

        foreach($collection as $item) {
            $gridValue[] = $this->fieldsValue($item);
        }

        return $gridValue;
    }

    public function viewCtx()
    {
        $resource = (new $this->model)->getTable();
        $pagination = $this->buildpagination();
        $rowIds = $pagination ? $pagination->pluck('id') : [];
        return [
            'elID' => $this->elId(),
            'title' => $this->title,
            'actions' => $this->actions(),
            'resource' => $resource,
            'pagination' => $pagination,
            'fields' => $this->fieldsMeta(),
            'values' => $this->gridValue($pagination),
            'rowIds' => $rowIds,
            'searchable' => $this->searchable,
            'q' => $this->searchable ? request('q'): null,
        ];
    }

    public function descID($descID=true) {
        $this->descID = $descID;
        return $this;
    }

    public function perPage($perPage) {
        $this->perPage = $perPage;
        return $this;
    }

    public function searchable($searchable=true) {
        $this->searchable = $searchable;
        return $this;
    }
}